import "./reset.css";
import dayjs from "dayjs";
import editForm from "../form/index.vue";
import { zxcvbn } from "@zxcvbn-ts/core";
import { message } from "@/utils/message";
import { usePublicHooks } from "../../hooks";
import { addDialog } from "@/components/ReDialog";
import type { PaginationProps } from "@pureadmin/table";
import type { FormItemProps } from "../utils/types";
import { getKeyList, isAllEmpty, deviceDetection } from "@pureadmin/utils";
import {
  getUserList,
  addUser,
  upUser,
  delUser,
  userEnable,
  resetPwd
} from "@/api/system/user";
import { getRoleList } from "@/api/system/role";
import { getStoreSimplePage } from "@/api/basicArchives/storeManagement";
import { dealTreeList } from "@/utils/common";

import {
  ElForm,
  ElInput,
  ElFormItem,
  ElProgress,
  ElMessageBox
} from "element-plus";
import {
  type Ref,
  h,
  ref,
  toRaw,
  computed,
  reactive,
  onMounted,
  watch
} from "vue";

export function useUser(tableRef: Ref) {
  const bizType = 2; // 业务类型 1平台端 2门店端
  const form = reactive({
    bizType: bizType,
    name: "",
    phone: "",
    status: "",
    enableStatus: "",
    pageNum: 1,
    pageSize: 10
  });
  const formRef = ref();
  const ruleFormRef = ref();
  const dataList = ref([]);
  const loading = ref(false);
  const switchLoadMap = ref({});
  const { switchStyle } = usePublicHooks();
  const treeData = ref([]);
  const selectedNum = ref(0);
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  });
  const columns: TableColumnList = [
    {
      label: "账号ID",
      prop: "id",
      width: 90
    },
    {
      label: "账号名称",
      prop: "name",
      minWidth: 130
    },
    {
      label: "账号",
      prop: "phone",
      minWidth: 130
    },
    {
      label: "角色",
      prop: "roleList",
      minWidth: 90,
      cellRenderer: ({ row }) => (
        <>
          {row.roleList.map(i => (
            <el-tag
              style={{ marginRight: "5px" }}
              type="primary"
              effect="plain"
            >
              {i.name}
            </el-tag>
          ))}
        </>
      )
    },
    // {
    //   label: "所属门店",
    //   prop: "storeIdList",
    //   minWidth: 90,
    //   cellRenderer: ({ row }) => (
    //     <>
    //       {getStoreName(row.storeIdList).map(i => (
    //         <el-tag
    //           style={{ marginRight: "5px" }}
    //           type="primary"
    //           effect="plain"
    //         >
    //           {i.storeName}
    //         </el-tag>
    //       ))}
    //     </>
    //   )
    // },
    {
      label: "状态",
      prop: "enableStatus",
      minWidth: 90,
      cellRenderer: scope => (
        <el-switch
          size={scope.props.size === "small" ? "small" : "default"}
          loading={switchLoadMap.value[scope.index]?.loading}
          v-model={scope.row.enableStatus}
          active-value={1}
          inactive-value={2}
          active-text="已启用"
          inactive-text="已停用"
          inline-prompt
          style={switchStyle.value}
          beforeChange={() => onChange(scope as any)}
        />
      )
    },
    {
      label: "创建人",
      prop: "createUserName",
      minWidth: 90
    },
    {
      label: "创建时间",
      minWidth: 90,
      prop: "gmtCreate",
      formatter: ({ gmtCreate }) => dayjs(gmtCreate).format("YYYY-MM-DD HH:mm")
    },
    {
      label: "操作",
      fixed: "right",
      width: 220,
      slot: "operation"
    }
  ];
  const buttonClass = computed(() => {
    return [
      "!h-[20px]",
      "reset-margin",
      "!text-gray-500",
      "dark:!text-white",
      "dark:hover:!text-primary"
    ];
  });
  // 重置的新密码
  const pwdForm = reactive({
    newPwd: ""
  });
  const pwdProgress = [
    { color: "#e74242", text: "非常弱" },
    { color: "#EFBD47", text: "弱" },
    { color: "#ffa500", text: "一般" },
    { color: "#1bbf1b", text: "强" },
    { color: "#008000", text: "非常强" }
  ];
  // 当前密码强度（0-4）
  const curScore = ref();
  const roleOptions = ref([]);
  const storeOptions = ref([]);
  const storeTreeData = ref([]);

  function onChange({ row, index }) {
    let enableStatus = 1;
    if (row.enableStatus == 1) {
      enableStatus = 2;
    }
    // userEnable enableStatus 使用状态 1正在使用 2禁用
    let optStr = row.enableStatus == 1 ? "停用" : "启用";
    ElMessageBox.confirm(
      `确认要<strong>${optStr}</strong><strong style='color:var(--el-color-primary)'>'${
        row.name
      }'</strong>用户吗?`,
      "系统提示",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        dangerouslyUseHTMLString: true,
        draggable: true
      }
    )
      .then(async () => {
        switchLoadMap.value[index] = Object.assign(
          {},
          switchLoadMap.value[index],
          {
            loading: true
          }
        );
        await userEnable({ id: row.id, enableStatus });
        row.enableStatus = enableStatus;
        message(optStr + "成功", {
          type: "success"
        });
        switchLoadMap.value[index] = Object.assign(
          {},
          switchLoadMap.value[index],
          {
            loading: false
          }
        );
      })
      .catch(() => {
        row.status === 0 ? (row.status = 1) : (row.status = 0);
      });
    return false;
  }

  function handleUpdate(row) {
    console.log(row);
  }

  const handleDelete = async row => {
    await delUser(row.id);
    message("删除成功", { type: "success" });
    onSearch();
  };

  function handleSizeChange(val: number) {
    console.log(`${val} items per page`);
    form.pageSize = val;
    onSearch();
  }

  function handleCurrentChange(val: number) {
    console.log(`current page: ${val}`);
    form.pageNum = val;
    onSearch();
  }

  /** 批量删除 */
  function onbatchDel() {
    // 返回当前选中的行
    const curSelected = tableRef.value.getTableRef().getSelectionRows();
    // 接下来根据实际业务，通过选中行的某项数据，比如下面的id，调用接口进行批量删除
    message(`已删除用户编号为 ${getKeyList(curSelected, "id")} 的数据`, {
      type: "success"
    });
    tableRef.value.getTableRef().clearSelection();
    onSearch();
  }

  async function onSearch() {
    loading.value = true;
    const { data } = await getUserList(toRaw(form));
    dataList.value = data.records || [];
    pagination.total = data.total;
    pagination.pageSize = data.pageSize;
    pagination.currentPage = data.pageNum;

    setTimeout(() => {
      loading.value = false;
    }, 500);
  }

  const resetForm = formEl => {
    if (!formEl) return;
    formEl.resetFields();
    onSearch();
  };

  function openDialog(title = "新增", row?: FormItemProps) {
    let tempRoleStoreList = [
      {
        roleId: roleOptions.value.length > 0 ? roleOptions.value[0].id : "",
        storeIds: []
      }
    ];
    if (title == "修改") {
      tempRoleStoreList = row.roleStoreList || [];
    }
    addDialog({
      title: `${title}账号`,
      props: {
        formInline: {
          id: row?.id ?? undefined,
          title,
          bizType: bizType,
          name: row?.name ?? "",
          password: row?.password ?? "",
          phone: row?.phone ?? "",
          roleIdList: row?.roleIdList ?? [],
          storeIdList: row?.storeIdList ?? [],
          roleOptions: roleOptions.value ?? [],
          storeTreeData: storeTreeData.value ?? [],
          roleStoreList: tempRoleStoreList
        }
      },
      width: "750px",
      draggable: true,
      fullscreen: deviceDetection(),
      fullscreenIcon: true,
      closeOnClickModal: false,
      contentRenderer: () => h(editForm, { ref: formRef, formInline: null }),
      beforeSure: (done, { options }) => {
        const FormRef = formRef.value.getRef();
        const curData = options.props.formInline as FormItemProps;
        function chores() {
          message("操作成功", {
            type: "success"
          });
          done(); // 关闭弹框
          onSearch(); // 刷新表格数据
        }
        FormRef.validate(async valid => {
          if (valid) {
            let newData = { ...curData };
            delete newData.roleOptions;
            delete newData.storeTreeData;
            // 表单规则校验通过
            if (title === "新增") {
              // 实际开发先调用新增接口，再进行下面操作
              await addUser(newData);
              chores();
            } else {
              // 实际开发先调用修改接口，再进行下面操作
              await upUser(newData);
              chores();
            }
          }
        });
      }
    });
  }

  watch(
    pwdForm,
    ({ newPwd }) =>
      (curScore.value = isAllEmpty(newPwd) ? -1 : zxcvbn(newPwd).score)
  );

  /** 重置密码 */
  function handleReset(row) {
    pwdForm.newPwd = "123456";
    addDialog({
      title: `重置 ${row.name} 用户的密码`,
      width: "500px",
      draggable: true,
      closeOnClickModal: false,
      fullscreen: deviceDetection(),
      contentRenderer: () => (
        <>
          <ElForm ref={ruleFormRef} model={pwdForm}>
            <ElFormItem
              prop="newPwd"
              rules={[
                {
                  required: true,
                  validator: (rule, value, callback) => {
                    if (value === "") {
                      callback(new Error("请输入新密码"));
                    } else if (value.length < 6) {
                      callback(new Error("密码长度不可小于6位"));
                    } else {
                      callback();
                    }
                  },
                  trigger: "blur"
                }
              ]}
            >
              <ElInput
                clearable
                show-password
                type="password"
                v-model={pwdForm.newPwd}
                placeholder="请输入新密码"
              />
            </ElFormItem>
          </ElForm>
          <div class="mt-4 flex mb-[16px]">
            {pwdProgress.map(({ color, text }, idx) => (
              <div
                class="w-[19vw]"
                style={{ marginLeft: idx !== 0 ? "4px" : 0 }}
              >
                <ElProgress
                  striped
                  striped-flow
                  duration={curScore.value === idx ? 6 : 0}
                  percentage={curScore.value >= idx ? 100 : 0}
                  color={color}
                  stroke-width={10}
                  show-text={false}
                />
                <p
                  class="text-center"
                  style={{ color: curScore.value === idx ? color : "" }}
                >
                  {text}
                </p>
              </div>
            ))}
          </div>
        </>
      ),
      closeCallBack: () => (pwdForm.newPwd = ""),
      beforeSure: done => {
        ruleFormRef.value.validate(async valid => {
          if (valid) {
            // 根据实际业务使用pwdForm.newPwd和row里的某些字段去调用重置用户密码接口即可
            await resetPwd({ id: row.id, password: pwdForm.newPwd });

            // 表单规则校验通过
            message(`已成功重置' ${row.name} '的密码`, {
              type: "success"
            });
            done(); // 关闭弹框
            // onSearch(); // 刷新表格数据
          }
        });
      }
    });
  }

  // const getStoreName = idList => {
  //   let storeList = [];
  //   if (idList.length > 0) {
  //     storeList = storeOptions.value.filter(v => idList.includes(v.id));
  //   }
  //   return storeList;
  // };

  onMounted(async () => {
    onSearch();

    // 角色列表
    let params = {
      bizType: bizType,
      pageNum: 1,
      pageSize: 300
    };
    const { data } = await getRoleList(params);
    roleOptions.value = data.records || [];

    // 门店列表获取
    const resData = await getStoreSimplePage({ status: 0, ...params });
    storeOptions.value = resData.data?.records || [];
    storeTreeData.value = dealTreeList(
      storeOptions.value,
      "areaId",
      "areaName",
      "storeName"
    );
  });

  return {
    form,
    loading,
    columns,
    dataList,
    treeData,
    selectedNum,
    pagination,
    buttonClass,
    deviceDetection,
    onSearch,
    resetForm,
    onbatchDel,
    openDialog,
    handleUpdate,
    handleDelete,
    handleReset,
    handleSizeChange,
    handleCurrentChange
  };
}
